package com.caiwangdai.app.ui.verify

import android.content.Context
import android.content.Intent
import android.os.CountDownTimer
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import com.afollestad.materialdialogs.MaterialDialog
import com.caiwangdai.app.Const
import com.caiwangdai.app.R
import com.caiwangdai.app.backend.RetrofitHome
import com.caiwangdai.app.backend.observer.OnDataV2Listener
import com.caiwangdai.app.backend.rx.RxSchedulers
import com.caiwangdai.app.bean.PayOrderB
import com.caiwangdai.app.bean.SignResultB
import com.caiwangdai.app.bean.base.BaseB
import com.caiwangdai.app.bean.base.NormalResponseB
import com.caiwangdai.app.extension.getContent
import com.caiwangdai.app.extension.setOnClickListenerPro
import com.caiwangdai.app.extension.showVerifyWaitingDialog
import com.caiwangdai.app.extension.toast
import com.caiwangdai.app.origin.BaseActivity
import com.caiwangdai.app.origin.ToolBarManager
import com.caiwangdai.app.pay.MobileSecurePayer
import com.caiwangdai.app.ui.borrow.BorrowIntentionActivity
import com.caiwangdai.app.utils.AuthUtils
import com.google.gson.Gson
import com.orhanobut.logger.Logger
import kotlinx.android.synthetic.main.activity_bank_verify.*

//实名认证
//银行卡
class RealNameVerifyActivity : BaseActivity() {
    override fun getLayoutResID() = R.layout.activity_bank_verify

    companion object {
        fun newInstance(context: Context): Intent {
            val intent = Intent(context, RealNameVerifyActivity::class.java)
            return intent
        }
    }

    override fun initView() {
        ToolBarManager.with(this, WMContent)
                .setTitle("实名认证")
                .setNavigationIcon(R.drawable.ic_nav_arrow_white)

        btn_submit.setOnClickListenerPro {
            if (checkAllValue()) actionSubmit()
        }
    }

    private fun checkAllValue(): Boolean {
        val bank = et_bank.getContent()
        val name = et_name.getContent()
        val number = et_number.getContent()
        if (bank.isEmpty()) {
            toast("请输入银行卡号")
            return false
        }
        if (name.isEmpty()) {
            toast("请输入真实姓名")
            return false
        }
        if (number.isEmpty()) {
            toast("请输入身份证号码")
            return false
        }
        if (!TextUtils.isEmpty(AuthUtils.IDCardValidate(number))) {
            toast(AuthUtils.IDCardValidate(number))
            return false
        }
        return true
    }

    private fun actionSubmit() {

        val bank = et_bank.getContent()
        val name = et_name.getContent()
        val number = et_number.getContent()
        //next step
        RetrofitHome
                .getHomeApi()
                .verifyRealName(bank, name, number)
                .compose(RxSchedulers.toMain())
                .subscribe(object : OnDataV2Listener<PayOrderB>(this) {

                    override fun onSuccess(value: NormalResponseB<PayOrderB>) {
                        super.onSuccess(value)
                        val obj = value.data?.data
                        val content = obj?.toJson()
                        Logger.e(content)
                        //bind
                        val msp = MobileSecurePayer()
                        msp.payRepaySign(content, mHandler, Const.RQF_PAY, this@RealNameVerifyActivity, false)
                    }
                })
    }

    val mHandler = MyHandler()

    inner class MyHandler : Handler() {

        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            val strRet = msg?.obj as String
            val result = Gson().fromJson(strRet, SignResultB::class.java)

            val retCode = result.ret_code
            val retMsg = result.ret_msg
            val resultPay = result.result_pay
            Logger.json(result.toJson())

            when (msg.what) {
                Const.RQF_PAY -> {
                    when (retCode) {
                        Const.RET_CODE_SUCCESS -> {
                            //  卡前置模式返回的银行卡绑定协议号，用来下次支付时使用，此处仅作为示例使用。正式接入时去掉
                            Logger.e("签约成功")
                            postSignInfo(result.no_agree)
                        }
                        Const.RET_CODE_PROCESS -> {
                            //  处理中，掉单的情形
                            if (Const.RESULT_PAY_PROCESSING == resultPay) {
                                Logger.e("操作失败，请重试")
                            }
                        }
                        else -> {
                            //  失败
                            Logger.e("操作失败，请重试")
                        }
                    }
                }
            }
        }
    }

    var isPostSingeInfo = false
    var isCdRunning = false


    lateinit var dialog: MaterialDialog

    fun postSignInfo(no_agree: String?) {
        //倒计时
        dialog = showVerifyWaitingDialog()
        val cd = object : CountDownTimer(6000, 1000) {

            override fun onFinish() {
                if (isPostSingeInfo) goVerifyResultPage()
                isCdRunning = false
            }

            override fun onTick(l: Long) {}
        }
        isCdRunning = true
        cd.start()

        //请求
        val bank = et_bank.getContent()
        val name = et_name.getContent()
        val number = et_number.getContent()
        //next step
        RetrofitHome
                .getHomeApi()
                .postSignInfo(number, name, bank, no_agree)
                .compose(RxSchedulers.toMain())
                .subscribe(object : OnDataV2Listener<BaseB>(this) {

                    override fun isShowProgressBar() = false

                    override fun onSuccess(value: NormalResponseB<BaseB>) {
                        isPostSingeInfo = true
                        if (!isCdRunning) {
                            goVerifyResultPage()
                        }
                    }

                })
    }

    fun goVerifyResultPage() {
        dialog.dismiss()
        startActivity(BorrowIntentionActivity.newInstance(mContext, true))
        onBackPressed()
    }
}
